package com.ssy.lingxi.message.websocket.config;

import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.basic.UserLoginSourceEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.component.redis.service.IRedisUtils;
import com.ssy.lingxi.message.websocket.session.WsSessionAttr;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;
import java.util.Objects;

/**
 * webSocket拦截器
 * @author yzc
 * @version 2.0.0
 * @date 2020/11/2
 */
public class SimpleWebSocketShakeInterceptor extends HttpSessionHandshakeInterceptor {

    private final IRedisUtils redisUtils;

    public SimpleWebSocketShakeInterceptor(IRedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 获取用户标识
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;

            // 获取token标识
            String token = serverRequest.getServletRequest().getParameter(WsSessionAttr.TOKEN);

            if (StringUtils.isBlank(token)) {
                return false;
            }

            // 是否有登录
            UserLoginCacheDTO loginUser = (UserLoginCacheDTO) redisUtils.get(token, Constants.REDIS_USER_INDEX);
            if (Objects.isNull(loginUser)) {
                return false;
            }

            // 平台后台session key特殊处理
            if (UserLoginSourceEnum.BUSINESS_MANAGEMENT_PLATFORM.getCode().equals(loginUser.getLoginSource())) {
                attributes.put(WsSessionAttr.SOURCE, loginUser.getLoginSource().toString());
                attributes.put(WsSessionAttr.MEMBER_ID, "0");
                attributes.put(WsSessionAttr.ROLE_ID, "0");
                attributes.put(WsSessionAttr.USER_ID, "0");
            } else {
                attributes.put(WsSessionAttr.SOURCE, loginUser.getLoginSource().toString());
                attributes.put(WsSessionAttr.MEMBER_ID, loginUser.getMemberId().toString());
                attributes.put(WsSessionAttr.ROLE_ID, loginUser.getMemberRoleId().toString());
                attributes.put(WsSessionAttr.USER_ID, loginUser.getUserId().toString());
            }
        }

        // 调用父方法,继续执行逻辑
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }
}